﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EussSimpleDBProvider
{
    static class SimpleDBConversion
    {
        static int maxint = 2147483647;

        public static string ToSDBString(object o)
        {
            Type t = o.GetType();

            if (t == typeof(string))
            {
                return (string)o;
            }
            else if (t == typeof(Guid))
            {
                return ((Guid)o).ToString();
            }
            else if (t == typeof(DateTime))
            {
                return ((DateTime)o).ToString("s");
            }
            else if (t == typeof(int))
            {
                long number = (int)o;
                number += maxint;
                string s = number.ToString();
                s.PadLeft(10, '0');
                return s;
            }
            else if (t == typeof(byte[]))
            {
                return Convert.ToBase64String((byte[])o);
            }
            else
            {
                throw new NotSupportedException(string.Format("The type {0} is not supported by the SimpleDB provider", t.FullName));
            }

        }

        public static object FromSDBString(string s, Type t)
        {

            if (t == typeof(string))
            {
                return s;
            }
            else if (t == typeof(Guid))
            {
                return new Guid(s);
            }
            else if (t == typeof(DateTime))
            {
                return DateTime.Parse(s);
            }
            else if (t == typeof(int))
            {
                long number = long.Parse(s);
                number -= maxint;
                return (int)number;
            }
            else if (t == typeof(byte[]))
            {
                return Convert.FromBase64String(s);
            }
            else
            {
                throw new NotSupportedException(string.Format("The type {0} is not supported by the SimpleDB provider", t.FullName));
            }
        }
    }
}
